import asyncio
import websockets
import json
import time
import socket

#TCP客户端
async def main_tcp(websocket):
    # # 创建socket对象
    # socket_client = socket.socket()
    # # 连接到服务器（即PLC）
    # socket_client.connect(("localhost", 8888))
    #不断地接受消息发送消息
    # 测试数据 '00 00 00 00 00 00 00 00 00 00' 正常手动模式
    #'01 00 00 00 00 00 00 00 00 00' 正常自动模式
    #'00 01 00 00 00 00 00 00 00 00' 火报
    #'00 00 01 00 00 00 00 00 00 00' 阀门开
    #'00 00 00 01 00 00 00 00 00 00' 通讯断
    #'00 00 00 00 01 00 00 00 00 00' 喇叭关闭

    recv_data = '00 01 00 00 00 00 00 00 00 00' 

    while True:
        # send_msg = input("请输入要发送给服务端的消息：")
        # if send_msg == "exit":
        #     break
        # # 发送消息
        # socket_client.send(send_msg.encode("UTF-8"))
        # 接受消息
        # recv_data = socket_client.recv(1024).decode("UTF-8")    # 1024是缓冲区大小，一般就填1024， recv是阻塞式
        print(f"服务端回复的消息是：{recv_data}")
        await websocket.send(json.dumps(recv_data))
    # 关闭连接
    socket_client.close()


async def send_messages(websocket):
    """不断发送消息给客户端"""
    counter = 0
    while True:
        """处理数据"""
        message = {
            "type": "status",
            "counter": counter,
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
        }
        await main_tcp(websocket)
        # print(f"发送消息: {message}")
        # counter += 1
        # await asyncio.sleep(2)  # 每2秒发送一次

async def handler(websocket):
    """处理客户端连接"""
    print("客户端已连接")
    try:
        await send_messages(websocket)
    except websockets.ConnectionClosed:
        print("连接关闭")
    finally:
        print("客户端断开连接")

async def main():
    """启动 WebSocket 服务器"""
    async with websockets.serve(handler, "localhost", 8765):
        print("WebSocket 服务器启动成功，监听地址: ws://localhost:8765")
        await asyncio.Future()  # 运行直到手动停止

if __name__ == "__main__":
    asyncio.run(main())

